from flask import Flask, request, jsonify
import subprocess
import os
import json
from typing import Optional, Dict
from dataclasses import dataclass
from get_video_by_selenium import ProcessResult  # 新增导入

app = Flask(__name__)

@dataclass
class ApiResponse:
    """API响应数据类"""
    code: int
    data: Optional[Dict]  # 修改为Dict类型以存储ProcessResult
    message: Optional[str]

def execute_douyin_process(douyin_url: str) -> ProcessResult:
    """执行抖音视频处理并返回结果对象"""
    python_src_dir = os.getenv('PYTHON_SRC_DIR', '.')
    cmd = f"cd {python_src_dir} && python ./get_video_by_selenium.py \"{douyin_url}\""
    
    process = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    stdout, stderr = process.communicate()
    
    # 保留调试输出
    print(f"[DEBUG] 子进程完整输出:\n{stdout}\n[DEBUG] 错误输出:\n{stderr}")
    
    if process.returncode == 0:
        try:
            # 提取result:后的JSON内容
            json_start = stdout.find("result:")
            if json_start == -1:
                raise ValueError("输出中未找到result标记")
                
            json_str = stdout[json_start + len("result:"):].strip()
            if not json_str:
                raise ValueError("result后内容为空")
                
            # 保留原始输出调试
            print(f"[DEBUG] 提取的JSON内容:\n{json_str}")
            
            result_dict = json.loads(json_str)
            return ProcessResult(**result_dict)
        except (json.JSONDecodeError, ValueError) as e:
            # 保留错误调试信息
            error_msg = f"解析输出失败: {str(e)}"
            print(f"[ERROR] {error_msg}")
            return ProcessResult(
                success=False,
                video_url=None,
                file_path=None,
                transcription=None,
                elapsed_times={},
                error=error_msg
            )
    else:
        # 保留子进程失败调试
        error_msg = f"子进程执行失败: {stderr}"
        print(f"[ERROR] {error_msg}")
        return ProcessResult(
            success=False,
            video_url=None,
            file_path=None,
            transcription=None,
            elapsed_times={},
            error=error_msg
        )

@app.route('/get_douyin_text', methods=['GET'])
def get_douyin_text():
    """处理抖音视频转文字请求"""
    douyin_url = request.args.get('douyin_url')
    sk = request.args.get('sk')  # 安全校验参数
    
    print(f"get_douyin_text {douyin_url} {sk}")
    if not douyin_url:
        response = jsonify(ApiResponse(
            code=400,
            data=None,
            message="Missing douyin_url parameter"
        ).__dict__)
        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return response
    
    # 执行处理并获取结果对象
    result = execute_douyin_process(douyin_url)
    print(f"get_douyin_text ok {result}")
    
    # 转换为API响应
    if result.success:
        response = jsonify(ApiResponse(
            code=0,
            data=result.__dict__,
            message="测试一"
        ).__dict__)
    else:
        response = jsonify(ApiResponse(
            code=500,
            data=None,
            message=result.error
        ).__dict__)
    
    # 设置响应头确保中文正常显示
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    return response

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify(ApiResponse(
        code=0,
        data="Service is running",
        message=None
    ).__dict__)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8010)
    
    